package com.lqclass.demo.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lqclass.demo.domain.User;
import com.lqclass.demo.service.impl.UserServiceImpl;
import com.lqclass.demo.utils.JsonData;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录过滤器
 */
//@WebFilter(urlPatterns = "/api/v1/pri/*", filterName = "loginFilter")
public class LoginFilter implements Filter {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 容器加载的时候
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("init LoginFilter=========");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("doFilter LoginFilter=========");

        HttpServletRequest req = (HttpServletRequest) servletRequest;

        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String token = req.getHeader("token");
        if(StringUtils.isEmpty(token)){
            token = req.getParameter("token");
        }

        if(StringUtils.isEmpty(token)){

            renderJson(resp, JsonData.buildError("未登录", -3));
            return;

        }

        // 判断token是否合法
        User user = UserServiceImpl.sessionMap.get(token);
        if(user != null){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        renderJson(resp, JsonData.buildError("登录失败，token无效", -2));
    }

    /**
     * 登录拦截，验证失败时，返回有效信息
     * @param response
     * @param jsonData
     * @throws JsonProcessingException
     */
    private void renderJson(HttpServletResponse response, JsonData jsonData) throws JsonProcessingException {

        String jsonStr = objectMapper.writeValueAsString(jsonData);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        try(PrintWriter writer = response.getWriter()){
            writer.print(jsonStr);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 容器销毁的时间
     */
    @Override
    public void destroy() {

        System.out.println("destroy LoginFilter=========");
    }
}
